package com.web;

import com.google.gson.Gson;
import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.utils.WebUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    UserService userService=new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名
        String username = req.getParameter("username");
        //判断用户名是否存在
        boolean existsUsername = userService.existsUsername(username);
        //返回用户是否存在
        Map<String,Object> result=new HashMap<>();
        // 如果用户存在，返回 result 为 1,如果用户不存在。result 返回 0
        result.put("existsUsername",existsUsername);
        //创建Gson对象实例
        Gson gson=new Gson();
        String toJson = gson.toJson(result);
        resp.getWriter().write(toJson);
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、销毁 Session 中用户登录的信息（或者销毁 Session）
        req.getSession().invalidate();
//        2、重定向到首页（或登录页面）
        resp.sendRedirect(req.getContextPath());
    }
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求参数
        String username = req.getParameter("username");//获取用户名
        String password = req.getParameter("password");//获取用户密码
        //2.调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        if (loginUser==null) {

            //3.如果等于 null,说明登录 失败!
            System.out.println("用户名或密码错误，登录失败");
            //把错误信息和回显的表单项信息。保存到域对象中
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("username",username);
            //返回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        } else {
            //4.如果不等于null，说明登录成功，跳转到登录成功页面
            System.out.println("登录成功");
            //保存用户登录之后的信息到session域中
            req.getSession().setAttribute("user",loginUser);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);

        }
    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 Session 中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //1.获取post请求传来的参数
        String username = req.getParameter("username");//获取用户名
        String password = req.getParameter("password");//获取用户密码
        String email = req.getParameter("email");//获取邮箱
        String code = req.getParameter("code");//获取验证码
        //将map中的值封装到user类中
        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());
        //2.检验验证码是否正确，
        if (token !=null && token.equalsIgnoreCase(code)) {//忽略大小写
            //若验证码正确,判断用户名是否可用
            if (userService.existsUsername(username)) {

                //若用户名已存在,
                System.out.println("用户名["+username+"]已存在");
                //把回显信息保存到域中
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                //跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                //若用户名不存在，则保存到数据库
                userService.registUser(new User(null,username,password,email));
                //再跳转到注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
                System.out.println("用户注册成功");

            }
        }else {
            //若验证码不正确，
            System.out.println("验证码["+code+"]错误");
            //把回显信息保存到域中
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            //返回注册页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

}
